package com.wxtools.util.http;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import com.aliyun.oss.model.PutObjectResult;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.UploadByOss;
import com.wxtools.bean.result.WxError;
import com.wxtools.exception.WxErrorException;
import com.wxtools.util.StringUtils;
import com.wxtools.util.file.FileUtils;

/**
 * 【二维码】素材请求下载器
 * 下载媒体文件POST请求执行器，请求的参数是String, 返回的结果是File
 * @author antgan
 *
 */
public class QrCodeDownloadPostRequestExecutor implements  RequestExecutor<String, String> {

	private File qrDirFile;
	

	public QrCodeDownloadPostRequestExecutor() {
		super();
	}

	public QrCodeDownloadPostRequestExecutor(File qrDirFile) {
		super();
		this.qrDirFile = qrDirFile;
	}

	@Override
	public String execute(CloseableHttpClient httpclient, String uri, String params)
			throws WxErrorException, ClientProtocolException, IOException {
	
		HttpPost httpPost = new HttpPost(uri);
		if (params != null) {
			httpPost.setEntity(new StringEntity(params,"UTF-8"));
		}
		
		try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
			Header[] contentTypeHeader = response.getHeaders("Content-Type");
			if (contentTypeHeader != null && contentTypeHeader.length > 0) {
				// 下载媒体文件出错
				if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
					String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
					throw new WxErrorException(WxError.fromJson(responseContent));
				}
			}
			InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
			String fileName = System.currentTimeMillis()+".jepg";
			if (StringUtils.isBlank(fileName)) {
				return null;
			}
			
			String[] name_ext = fileName.split("\\.");
			
			File localFile = FileUtils.createMaterialFile(inputStream, name_ext[0], name_ext[name_ext.length-1], qrDirFile);
			
			String path =uploadImg(localFile, localFile.getName());
			localFile.delete();
			
			System.out.println(localFile.getPath());
			return path;
		}
	}
	
    public static String getExtension(String fileName) throws Exception {

        if (null != fileName) {
            int pos = fileName.lastIndexOf(".");
            if (pos > 0) {
                return fileName.substring(pos);
            }

        }
        return "";

    }
    
    private String uploadImg(File img,String fileName)
    {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR=Constant.Mini_Program_Share_QRCODE_DIR+"/"+System.currentTimeMillis()+tailSuffix;
            PutObjectResult result=UploadByOss.uploadByOss(img,DIR);
            if (null!=result)
            {
                return DIR;
            }else
            {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

}
